<?php

namespace app\api\controller;

use app\admin\controller\goods\Specs;
use app\admin\model\Banner;
use app\admin\model\config\Agreement;
use app\admin\model\config\Basics;
use app\admin\model\config\Subtitle;
use app\admin\model\goods\Goods;
use app\admin\model\goods\ShopGoodsSpecs;
use app\admin\model\shop\Shop;
use app\admin\model\shop\ShopGoodsBind;
use app\admin\model\user\Address;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\helpers\MapUtil;
use think\Db;
use think\db\Expression;
use think\Log;
use think\Model;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['rollindex','bannerList','agreementInfo','advert'];
    protected $noNeedRight = ['*'];

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 首页滚动字幕
     */
    public function rollindex()
    {
        $subtitleList = Subtitle::field('payment_user,payment_avatar,order_user,order_avatar,describe')
            ->where('status','1')->order('create_time desc')->select();
        if(count($subtitleList) == 0){
            $subtitleList=[];
            $order_list = \app\admin\model\shop\Order::where("payment_time","exp","is not null")->order('payment_time desc')->limit(0,5)->select();
            if($order_list){
                $user_id_list = array_unique(array_merge(array_column($order_list,'uid'),array_column($order_list,'payment_user_id')));
                $user_list=\app\admin\model\User::where('id','in',$user_id_list)->field('id,nickname,avatar')->select();
                $user_list = array_column($user_list,null,'id');
                foreach ($order_list as $v){
                    $subtitleList[]=[
                        'payment_user'=>$user_list[$v['payment_user_id']]['nickname'] ?? '',
                        'payment_avatar'=>$user_list[$v['payment_user_id']]['avatar'] ?? '',
                        'order_user'=>$user_list[$v['uid']]['nickname'] ?? '',
                        'order_avatar'=>$user_list[$v['uid']]['avatar'] ?? '',
                        'describe'=>"上了一杯".$v['goods_name']."！",
                    ];
                }
            }

        }
        $this->success('successful', $subtitleList);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 首页banner
     */
    public function bannerList()
    {
        $bannerList = Banner::field('img,sort')
            ->where('status','1')->order('sort desc')->select();
        $this->success('successful', $bannerList);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 相关协议
     */
    public function agreementInfo()
    {
        $type = $this->request->post('type');
        $banner = Agreement::get(['id'=>$type]);
        $this->success('successful', $banner);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 过屏广告
     */
    public function advert()
    {
        $info = Basics::get(['id'=>1]);
        $this->success('successful', ['img'=>ImageUtil::handle($info['advert_img']),'is_open'=>$info['is_open']]);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 点餐-地址
     */
    public function dcAddress()
    {
        $userInfo = $this->auth->getUserinfo();
        $address_id = $this->request->param('address_id');
        $data=[];
        if($address_id){
            $info = Address::get(['id'=>$address_id,'uid'=>$userInfo['id']]);
            $data['mobile'] = $info['mobile'];
            $data['user_name'] = $info['name'];
            $data['address'] = $info['address'];
            $data['lng'] = $info['lng'];
            $data['lat'] = $info['lat'];
        }else{
            $lng = $this->request->param('lng');
            $lat = $this->request->param('lat');
            $info = Address::get(['is_default'=> 1,'uid'=>$userInfo['id']]);
            $address = MapUtil::getAdress($lng,$lat);
            if($info){
                $data['mobile'] = $info['mobile'];
                $data['user_name'] = $info['name'];
                $data['address'] = $info['receipt_address'];
                $data['lng'] = $info['lng'];
                $data['lat'] = $info['lat'];
            }else{
                $data['mobile'] = $userInfo['mobile'];
                $data['user_name'] = $userInfo['nickname'];
                $data['address'] = $address;
                $data['lng'] = $lng;
                $data['lat'] = $lat;
            }
        }
        $shop_id = $this->request->param('shop_id');
        if($shop_id){
            $shop = Shop::get(['id'=>$shop_id,'status'=>'1','is_del'=> '0']);
            if(!$shop){
                $this->error("店铺已下架或已注销,请重新选择店铺");
            }
        }else{
            $shop = Shop::field(new Expression("*,ACOS(
            COS(RADIANS(".$data['lat'].")) *
            COS(RADIANS(lat)) *
            COS(RADIANS(lng) - RADIANS(".$data['lng'].")) +
            SIN(RADIANS(".$data['lat'].")) *
            SIN(RADIANS(lat))
            ) * 6378.137 as distance"))
                ->where('status','1')
                ->where('is_del','0')
                ->order('distance')->find();
            if(!$shop){
                $this->error("没有店铺信息");
            }
        }
        $data['shop_name'] = $shop['shop_name'];
        $data['shop_id'] = $shop['id'];
        $this->success('successful', $data);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 点餐-商品列表
     */
    public function dcGoodsList()
    {
        $shop_id = $this->request->param('shop_id');
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',5);//每页展示数量
        if(!$shop_id){
            $this->error("请选择商铺");
        }
        $shopInfo = Shop::get($shop_id);
        if($shopInfo['is_del'] != '0' || $shopInfo['status'] != '1'){
            $this->error("店铺已下架或已注销，请重新选择店铺");
        }
        $model = (new ShopGoodsBind())->alias('b')
            ->field('shop_id,id,name,price,content,imgs')
            ->join('shop_goods g','g.id = b.goods_id','LEFT')
            ->where('shop_id',$shop_id)
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        if($list){
            foreach ($list as $v){
                $v['imgs'] = ImageUtil::handle($v['imgs']);
            }
        }
        $this->success('successful', array("total" =>$total , "list" => $list));
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 地址与定位
     */
    public function addressLocation()
    {
        $user = $this->auth->getUserinfo();
        $list =  Address::Where('uid',$user['id'])->field('id,name,mobile,address,receipt_address,is_default')->select();
        $shop_id = $this->request->param('shop_id');
        //配合前端给出数据
        if(!$shop_id){
            $shopData =[];
        }else{
            $lng = $this->request->param('lng');
            $lat = $this->request->param('lat');
            $shop = Shop::get(['id'=>$shop_id]);
            if(!$shop || ($shop['status'] == '2' || $shop['is_del'] == '1')){
                $shopData =[];
            }else{
                $shopData=[
                    "shop_name"=>$shop['shop_name'],
                    "address"=>$shop['address'],
                    "business_hours"=>$shop['business_hours'],
                    "distance"=> MapUtil::distance($lat,$lng,$shop['lat'],$shop['lng']),
                    "shop_id"=> $shop_id //当前店铺id
                ];
            }
        }
        $this->success('successful', array("shop" =>$shopData , "addres" => $list));
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 选择店铺
     */
    public function shopList()
    {
        $city_id = $this->request->param('city_id');
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');
        $page = $this->request->param('page',1);//页码
        $pageSize = $this->request->param('pageSize',10);//每页展示数量
        $where['status'] = '1';
        $where['is_del'] = '0';
        if($city_id){
            $where['city'] = $city_id;
        }
        $model = (new Shop())
            ->field(new Expression("id,shop_name,address,business_hours,ACOS(
            COS(RADIANS(".$lat.")) *
            COS(RADIANS(lat)) *
            COS(RADIANS(lng) - RADIANS(".$lng.")) +
            SIN(RADIANS(".$lat.")) *
            SIN(RADIANS(lat))
            ) * 6378.137 as distance
            "))
            ->where($where)
            ->order('distance desc')
            ->paginate($pageSize, '', ['page' => $page, 'list_rows' => $pageSize]);
        $total= $model->total();
        $list =  $model->items();
        $this->success('successful', array("total" =>$total , "list" => $list));
    }

    /**
     * 获取市级区域
     */
    public function cityList()
    {
       $cityList =  Db::name('area')->field(['id,name,first'])->where('level',2)->where('code','not in',[',null'])->select();
       $this->success('successful', $cityList);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取商品信息
     */
    public function goodsDetails()
    {
        $goods_id= $this->request->param('goods_id');
        $shop_id= $this->request->param('shop_id');
        $goods = Goods::field('id,name,price,content,imgs')->where(['id'=>$goods_id])->find();
        if(!$goods) $this->error("商品信息不存在");
        $SpecsOneList = collection(ShopGoodsSpecs::field('id,name')->where(['status'=>1,'pid'=>0])->select())->toArray();
        if($SpecsOneList){
            $SpecsTwoList = ShopGoodsSpecs::where('pid','<>',0)->where('status',1)->select();
            foreach ($SpecsOneList as &$v){
                foreach ($SpecsTwoList as $vs){
                    if($v['id'] == $vs['pid']){
                        $v['child'][]=$vs;
                    }
                }
            }
        }
        $goods['shop_id'] =$shop_id;
        $goods['test'] = $SpecsOneList;
        $this->success('successful', $goods);
    }






}
